/**
 * widget-box drag and drop
 */
(function(){
    var $widgetBox;
    var offX = 0, offY = 0;

    $("body").on("mousedown", ".widget-header", function(e){
        $widgetBox = $(e.currentTarget).closest(".widget-box");
        if($widgetBox.length > 0){
            $widgetBox.addClass(".widget-box-moving");
            $widgetBox.css({
                position    : "relative",
                zIndex      : 9999,
                top         : "0px",
                left        : "0px"
            });
            offX = e.clientX;
            offY = e.clientY;
        }
    });

    $("body").on("mousemove", function(e){
        if($widgetBox)
            $widgetBox.css({
                top     : (e.clientY - offY) + "px",
                left    : (e.clientX - offX) + "px"
            });
    });

    $("body").on("mouseup", function(e){
        if($widgetBox){
            $widgetBox.removeClass(".widget-box-moving");
            $widgetBox.css({
                position: "static"
            });
            var dropFn = function(e){
                var $dropBox = $(e.currentTarget).parent();
                if($(e.currentTarget) != $widgetBox) {
                    $widgetBox.parent().append($(e.currentTarget));
                    $dropBox.append($widgetBox);
                }
                $widgetBox = null;
                $("body").off("mouseover", ".widget-box", dropFn);
            };
            $("body").on("mouseover", ".widget-box", dropFn);
            $("body").on("mousemove", ".widget-box", function(){
                $("body").off("mouseover", ".widget-box", dropFn);
            });
            $widgetBox.hide();
            $widgetBox.show();
        }
    });
})();
